<template>
  <div class="app-container">
    <ai_nabar style="margin: 10px 0 10px 0px;" index="1"></ai_nabar>
    <!-- 查询部分 -->
    <el-form :model="queryParams" class="frominfo" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">

      <el-form-item label="文件名称" prop="fileNam">
        <el-input v-model="queryParams.fileNam" @keyup.enter.native="handleQuery" placeholder="请输入文件名称" clearable />
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
          <el-option v-for="dict in dict.type.sys_file_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="设置时间" prop="createTime">
        <el-date-picker v-model="chatTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>
    <!-- 新增按钮部分 -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="file">导入文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">添加关键词</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['arbit:wcviolatemonitor:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="handleExport">批量导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">批量删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 信息栏部分 -->
    <el-table v-loading="loading" :data="wcViolateMonitorList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="文件名称" prop="fileName" align="center" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="类型" prop="fileType" align="center" :show-overflow-tooltip="true" /> -->

      <el-table-column label="类型" prop="fileType" align="center" :show-overflow-tooltip="true"/>

      <!-- <el-table-column label="大小" prop="fileSize" align="center" :show-overflow-tooltip="true" /> -->
      <!-- 使用插槽的方式给其加上单位 -->
      <el-table-column label="大小" align="center">
        <template slot-scope="scope">
          {{ scope.row.fileSize }} MB
        </template>
      </el-table-column>

      <el-table-column label="添加时间" prop="createTime" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" prop="remark" align="center" :show-overflow-tooltip="true" /> -->
      <el-table-column label="文件详情" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">详情</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 导入文件对话框 -->
    <el-dialog :title="title" :visible.sync="fileopen" width="1000px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px" class="file_box">
        <div class="left">
          <!-- 上传组件 -->
          <el-upload class="upload-demo" drag action="uploadUrl" :http-request="handleUpload" multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- <div style="margin-top: 10px;"><em @click="click_here">点击此处查看列表</em></div> -->
            <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </div>
        <div class="img" style="width: 20px; height: 20px;">
          <img src="../../../assets/images/chuanshu.png" alt="" style="width: 100%;height: 100%;" @click="transferData">
        </div>
        <div class="right">
          缓存上传：
          <el-table v-loading="loading" :data="caching_data" @selection-change="handleSelectionChange" class="right_one">
            <!-- <el-table-column type="selection" align="center" :show-overflow-tooltip="true" /> -->
            <el-table-column label="文件名称" prop="fileName" align="center" :show-overflow-tooltip="true" />
            <el-table-column label="类型" prop="fileType" align="center" :show-overflow-tooltip="true"/>
             
            <el-table-column label="大小" prop="fileSize" align="center" :show-overflow-tooltip="true"/>

            <el-table-column label="导入日期" prop="createTime" align="center" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>

            <el-table-column label="" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteone(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div>
        <h2 style="margin-left: 21%;" v-if="showUpload">OR</h2>
      </div>
      <div style="margin-left: 4%;" v-if="showUpload">
        <!-- <input type="text" v-model="uploadLink" placeholder="请输入上传链接" style="width: 80%; margin-right: 10px;"> -->
        <el-input v-model="uploadLink" @keyup.enter.native="handleUploadLink" placeholder="请输入文件名称" clearable
          style="width: 30%; margin-right: 10px;" />
        <el-button type="primary" @click="handleUploadLink">上传链接</el-button>
      </div>
      <div slot="footer" class="dialog-footer" style="position: relative; left: -38%;">
        <el-button @click="cancelone" style="margin-right: 10%;">取 消</el-button>
        <el-button type="primary" @click="submitFormone">上传</el-button>
      </div>
    </el-dialog>
    <!-- 添加违规词监测对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="新建名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <span style="font-size: 14px;margin-right: 10px;color: #333;margin-left: 13px;">新建标签</span>
        <div style="width: 280px;margin: 10px 0 50px 80px;">
          <el-input placeholder="请输入标签名" v-model="inputText" class="input-with-select">
            <el-button slot="append" @click="addKeyword">保存</el-button>
          </el-input>
        </div>
        <div style="margin-top: 20px;" class="dia-box-lable">
          <span style="font-size: 14px;color: #9aa5aa; ">已添加：</span>
          <el-tag v-for="(keyword, index) in whole" :key="index" closable @close="handleTagClose(keyword)" style="margin-right: 5px;">
            {{ keyword }}
          </el-tag>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import request from '@/utils/request'
import ai_nabar from '../components/ai_nabar.vue'
import * as XLSX from 'xlsx';
export default {
  components: {
    ai_nabar
  },
  name: "WcViolateMonitor",
  dicts: ['sys_file_type'],
  data() {
    return {
      uploadLink: '', // 用于存储输入的上传链接
      showUpload: true, // 控制显示上传组件还是文件列表
      inputText: '',
      whole: [],//新增加的关键词
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 违规词监测表格数据
      wcViolateMonitorList: [],

      chatTime: [],
      caching_data: [],   //缓存文件表格数据
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      fileopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileType: null,
        fileNam: null,
        beginTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
    // this.loading = false;
  },
  methods: {
    // 将文件拖到此处或点击上传
    handleUpload(file) {
      // 创建一个FormData对象，它是一种特殊格式的对象，可以模拟表单数据，
      let formData = new FormData();
      formData.append('file', file.file); // 将上传的文件添加到formData对象中 'file'是接口需要的参数名
      File_upload(formData).then(response => {
        this.caching_data.push(response);
      });
    },
    // 输入链接地址上传文件
    handleUploadLink() {
      //console.log(this.uploadLink, '地址');
      // 由于是 GET 请求，我们不需要 FormData 对象
      // 直接使用请求函数，并传递参数
      uploadLink_upload(this.uploadLink).then(response => {
        this.caching_data.push(response);
        if (response.code == 200) {
          this.uploadLink = '';
        }
      });
    },
    // 导入框中，点击切换的图片
    transferData() {
      const selectedRows = this.wcViolateMonitorList.filter(item => this.ids.includes(item.id));
      const selectedRowsInCaching = this.caching_data.filter(item => this.ids.includes(item.id));

      if (selectedRows.length > 0) {
        //将selectedRows数组中的所有元素添加到caching_data数组中
        this.caching_data = [...this.caching_data, ...selectedRows];
        // 从wcViolateMonitorList数组中移除所有被选中的行
        this.wcViolateMonitorList = this.wcViolateMonitorList.filter(item => !this.ids.includes(item.id));
      }

      if (selectedRowsInCaching.length > 0) {
        this.wcViolateMonitorList = [...this.wcViolateMonitorList, ...selectedRowsInCaching];
        this.caching_data = this.caching_data.filter(item => !this.ids.includes(item.id));
      }

      this.ids = []; // 清空选中状态
      // this.showUpload = false;
    },
    // 点击 ‘上传’按钮

    submitFormone() {
      // 构建请求参数数组，确保使用新的属性名fileUrl
      this.caching_data = this.caching_data.map(file => {
        return {
          fileName: file.fileName, // 文件名称
          fileSize: file.fileSize, // 文件大小
          fileType: file.fileType, // 文件类型
          fileUrl: file.ServerfileName, // 使用file.ServerfileName为fileUrl属性赋值
          createTime: file.createTime // 创建时间
        };
      });
      // 调用接口
      submitFormone(this.caching_data).then(res => {
        this.fileopen = false; // 关闭对话框
        this.getList(); // 重新获取列表数据

        // 清除已上传成功的文件
        this.caching_data = this.caching_data.filter(file => file.ServerfileName === '');
      });
    },

    cancelone() {
      this.fileopen = false;
      this.reset();
    },
    // 处理标签关闭事件
    handleTagClose(keyword) {
      this.whole = this.whole.filter(item => item !== keyword);
    },
    addKeyword() {
      if (this.inputText.trim() !== "") {
        this.whole.push(this.inputText.trim());
        this.inputText = ""; // 清空输入框
      }
    },

    /** 查询违规词监测列表 */
    getList() {
      this.loading = true;
      const form = {}; // 构造一个GetWcViolateMonitorListFORM对象
      listWcViolateMonitor(this.queryParams, form).then(res => {
        this.wcViolateMonitorList = res.data.rows;
        const dt = res['data'];
        this.total = dt['total'];
        this.loading = false;
      });
      setTimeout(()=>{
        this.loading = false;
      },2000)
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        fileType: null,
        fileName: null,
        createTime: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      if (this.chatTime != '' && this.chatTime != null) {
        this.queryParams.beginTime = this.chatTime[0]+' 00:00:00'
        this.queryParams.endTime = this.chatTime[1]+' 23:59:59'
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.chatTime=[]
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length

      // 确保只处理当前选中的数据项

    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加违规词监测";
    },
    // 导入按钮
    file() {
      this.reset();
      this.fileopen = true;
      this.title = "导入文件";
      this.showUpload = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //console.log(row.fileUrl)
      if(row.fileUrl!=''&&row.fileUrl!=null){
            const URL = window.URL || window.webkitURL;
            const downloadElement = document.createElement("a");
            const href = process.env.VUE_APP_BASE_API+row.fileUrl;
            downloadElement.href = href;
            downloadElement.download = new Date().getTime();
            document.body.appendChild(downloadElement);
            downloadElement.click(); 
            document.body.removeChild(downloadElement); 
            URL.revokeObjectURL(href);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.words = this.whole;
          if (this.form.id != null) {
            updateWcViolateMonitor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWcViolateMonitor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除违规词监测编号为"' + ids + '"的数据项？').then(function () {
        return delWcViolateMonitor(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    handleDeleteone(row) {
      const ids = row.ServerfileName || this.createTime;
      const index = this.caching_data.findIndex(item => item.ServerfileName === ids || item.createTime === ids);

      if (index !== -1) {
        this.$modal.confirm('是否确认删除违规词监测编号为"' + ids + '"的数据项？').then(() => {
          this.caching_data.splice(index, 1);
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
          // 用户点击取消，不做任何操作
        });
      } else {
        this.$modal.msgError("未找到对应的数据项");
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      if (this.ids.length > 0) {
        this.exportExcel()
      } else {
        this.$message.warning('请选择要导出的数据！');
      }
    },
    exportExcel() {
      // 假设你有一个表格数据的数组
      const data = [["文件名称", "类型", "大小", "添加时间"],]; // 根据您的需求，这里应该是您想要导出的列标题

      // 遍历this.ids，找到对应的记录，并添加到data中
      this.ids.forEach(id => {

        const record = this.wcViolateMonitorList.find(item => item.id === id);
        if (record) {
          // 添加记录到data数组中，根据您的需求，这里应该是记录的对应字段
          data.push([record.fileName, record.fileType, record.fileSize, record.createTime]);
        }
      });

      // 如果没有选中任何记录，则返回
      if (data.length === 1) {
        this.$message.warning('请选择要导出的数据！');
        return;
      }

      // 将数据转换为工作表
      const ws = XLSX.utils.aoa_to_sheet(data);

      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 生成Excel文件
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      // 字符串转ArrayBuffer
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }

      // 保存文件
      saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), `selected_wcRemindMonitor_${new Date().getTime()}.xlsx`);
    }
  }
};

/** js请求 调用 */

// 查询违规词监测列表
export function listWcViolateMonitor(query, form) {
  return request({
    url: '/wxassistant/wcviolate_monitor/GetWcViolateMonitorList',
    method: 'POST',
    params: query,
    data: form
  })
}

// 查询违规词监测详细
export function getWcViolateMonitor(id) {
  return request({
    url: '/arbit/wcviolate_monitor/queryById/' + id,
    method: 'get'
  })
}

// 新增违规词监测
export function addWcViolateMonitor(data) {
  return request({
    url: '/wxassistant/wcviolate_monitor/AddWcViolateMonitorKey',
    method: 'post',
    data: data
  })
}

// 修改违规词监测
export function updateWcViolateMonitor(data) {
  return request({
    url: '/arbit/wcviolate_monitor/edit',
    method: 'put',
    data: data
  })
}

// 删除违规词监测
export function delWcViolateMonitor(id) {
  return request({
    url: '/wxassistant/wcviolate_monitor/delete/' + id,
    method: 'delete'
  })
}


// 文件上传
export function File_upload(formData) {
  return request({
    url: '/common/Addupload',
    method: 'POST',
    data: formData, // 请求体数据为前面构造的formData对象。
  })
}
// 输入地址上传
// export function uploadLink_upload(url) {
//   return request({
//     url: '/common/AddUrlupload',
//     method: 'get',
//     params: url
//   });
// }
export function uploadLink_upload(url) {
  return request({
    url: '/common/AddUrlupload',
    method: 'get',
    params: {
      url: url // 将上传链接作为参数传递
    }
  });
}
// 上传缓存文件
export function submitFormone(data) {
  return request({
    url: '/wxassistant/wcviolate_monitor/AddWcViolateMonitor',
    method: 'post',
    data: data // 使用 data 代替 params   data通常用于发送POST请求的请求体（request body），而params通常用于URL查询参数（query parameters）
  });
}

</script>


<style lang="scss" scoped>
.app-container {
  background-color: #f6f9fb;
}

.file_box {
  display: flex;

  justify-content: space-between;
  /* 用于在.left和.right之间留出空间，如果不需要可以删除 */
  width: 100%; // 确保 .file_box 有足够的宽度
}

.left,
.img,
.right {
  display: flex;
  flex-direction: column;

}

.left,
.right {
  // flex: 40%;
  // height: 200px;
  // overflow-y: auto; /* 如果内容超出，则显示滚动条 */
  flex: 1; // 使用 flex: 1 以便它们可以响应式地占据空间
  max-width: 50%; // 限制最大宽度为 40%
  height: 220px;
  overflow-y: auto; // 如果内容超出，则显示滚动条

  .right_one {
    width: 100%;
    height: 200px;
    overflow-y: auto; // 如果内容超出，则显示滚动条
  }
}

.img {
  align-self: center;
  position: absolute;
  left: 45%;
  /* 使.img在中间位置 */
}

.dialog-footer {
  width: 100%;
  /* 确保.dialog-footer占据整个宽度 */
  margin-top: 20px;
  /* 在.dialog-footer前添加一些间距 */
}

.upload-demo {
  // 添加您想要的样式
  margin-top: 20px; // 添加顶部间距
  margin-left: 40px;

  // ... 其他样式 ...
}

.dia-box-lable {
  width: 90%;
  border-radius: 5px;
  border: 1px solid #eee;
  min-height: 100px;
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
  margin-bottom: 20px;

  .lable-box {
    padding: 0 5px;
    height: 20px;
    line-height: 20px;
    margin-right: 10px;
    border: 1px solid #dcdcdc;
    background-color: #ebf4ff;
    font-size: 12px;
    border-radius: 3px;
  }

  .select {
    color: #fff;
    background-color: #4095e5;
  }
}
</style>
